package cate.game.server.cli;

import cate.game.ManyGame;
import easy.socket.initial.WsServerInitializer;
import easy.socket.server.EasyServer;
import easy.socket.server.ServerProperties;
import easy.socket.util.NettyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/** 客户端通讯 */
@Slf4j
@Component
public class CliCommunication implements InitializingBean, DisposableBean {

    final ManyGame games;
    final EasyServer server = new EasyServer();

    public CliCommunication(ManyGame games) {
        this.games = games;
    }

    @PostConstruct
    public void init(){
        log.info("客户端通讯模块 init");

        ServerProperties properties = new ServerProperties();
        properties.host = games.config.wsHost;
        properties.ssl = NettyUtil.sslByScheme(games.config.wsScheme);
        properties.port = games.config.wsPort;
        properties.wsPath = games.config.wsPath;
        server.properties(properties);
        WsServerInitializer initializer = new WsServerInitializer();
        initializer.properties(properties);
        initializer.businessHandlerBuilder((ch) -> new CliHandler(properties, this.games));
        server.initializer(initializer);
        new Thread(() -> {
            try {
                server.start();
            } catch (Exception e) {
                log.error("", e);
            }
        }).start();
    }

    @Override
    public void afterPropertiesSet() {
        log.info("客户端通讯模块 afterPropertiesSet");
    }

    @Override
    public void destroy() {
        log.info("客户端通讯模块 destroy");
        server.stop();
    }

}
